<?php

namespace App\Http\Middleware;

use App\Models\Member\User;
use Closure;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

class ApiTokenMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if(empty($request->api_token)){
            return response()->json(['code'=>'621','data'=>'','msg'=>'缺少TOKEN']);
        }
        try {
            $api_token = Crypt::decryptString($request->api_token);
        } catch (DecryptException $e) {
            return response()->json(['code'=>'622','data'=>'','msg'=>'非法TOKEN']);
        }
        $user = User::where('api_token',$api_token)->first();
        if($user){
            if($user->api_token_expire<time()){
                //return response()->json(['code'=>'624','data'=>$user->api_user_data(),'msg'=>'TOKEN过期']);
            }else if($user->status=='-1'){
                return response()->json(['code'=>'625','data'=>'','msg'=>'账号被冻结']);
            }
            $request->api_user = $user;
        }else{
            return response()->json(['code'=>'623','data'=>'','msg'=>'请重新登录']);
        }
        return $next($request);
    }
}
